<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="仓库名称">
        <el-input v-model="query.storeName" clearable />
      </el-form-item>
      <el-form-item label="所属机构" prop="reId">
        <el-tree-select
          v-model="query.reId"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="关联类型">
        <el-select v-model="query.reType" placeholder="请选择" clearable>
          <el-option
            v-for="item in reTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="创建时间">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择">
          <el-option :value="2" label="已审核" />
          <el-option :value="-1" label="已作废" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-folder-add" @click="batchAdd">批量新增</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" :re-type-map="reTypeMap" />
    <batch-add ref="batchAdd" :re-type-map="reTypeMap" :tree-data="treeData" />
    <remark-order ref="remarkOrder" />
    <store-warning ref="storeWarning" />
    <detail ref="detail" />
  </div>
</template>

<script>
  import {
    queryWarehouseList,
    queryMap,
    warehouseDelete
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import RemarkOrder from '../../components/RemarkOrderModal'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import Add from './components/Add'
  import BatchAdd from './components/BatchAdd'
  import StoreWarning from './components/StoreWarning'
  import Detail from './components/Detail'

  export default {
    name: 'warehouseManage',
    components: {
      Add, RemarkOrder, BatchAdd, StoreWarning, Detail
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        reTypeMap: [],
        date: [],
        query: {
          storeName: '',
          reType: '',
          reId: '', // 所属机构orgSNNo
          status: 2
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        return [
          {
            prop: 'storeCode',
            label: '仓库编码'
          },
          {
            prop: 'storeName',
            width: 150,
            label: '仓库名称',
            render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.storeName}</el-link>
          },
          {
            prop: 'reType',
            label: '关联类型',
            render: (h, { row }) => <span>{ row.reType && formatColumnMap(this.reTypeMap, 'value', row.reType, 'desc') }</span>
          },
          {
            prop: 'rName',
            label: '关联名称'
          },
          {
            prop: 'director',
            label: '主管'
          },
          {
            prop: 'directorTel',
            label: '联系电话'
          },
          {
            prop: 'status',
            label: '状态',
            render: (h, { row }) => {
              if (row.status === 1) {
                return '未审核'
              } else if (row.status === 2) {
                return '已审核'
              } else {
                return '已作废'
              }
            }
          },
          {
            prop: 'createUser',
            label: '创建人'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-link size='mini' onClick={() => this.update(row, $index)}>
                    编辑
                  </el-link>
                  <el-link size='mini' onClick={() => this.storeWarning(row, $index)}>
                    库存预警
                  </el-link>
                  {row.status !== -1 && <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    作废
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.createTime = this.date[0].format()
          query.createTimeEnd = this.date[1].format()
        }
        const res = await queryWarehouseList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'StoreHouseReType' })
        this.reTypeMap = res.data // 库房关联类型
      },
      async add() {
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async storeWarning(row) {
        await this.$refs.storeWarning.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async batchAdd() {
        await this.$refs.batchAdd.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      del(row, index) {
        this.$confirm('确定要作废该仓库？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          warehouseDelete({ storeId: row.storeId }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$notify({
              title: '提示',
              message: '作废成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
